/**
 * Created by Administrator on 2017/5/23 0023.
 */

//编写渲染饼状图的函数
function renderPie(data,i){
    // 基于准备好的dom，初始化echarts实例

    var pieChart = [];
    pieChart[i] = echarts.init(document.getElementById('pie'+i));

    // 指定图表的配置项和数据
    var option = [];
    option[i] = {
        title: {
            text: data[i].ratio + '%',
            x:'center',
            y:'center',
            textStyle: {
                fontSize: 12,
                color: '#5b667a'
            }
        } ,

        series: [{
            name: data[i].region,
            type: 'pie',
            radius: ['83.4%', '100%'],
            data: [{
                value: data[i].ratio,
                name: '新增百分比',
                label: {
                    normal: {
                        show: false,
                        position: 'center'
                    }
                },
                itemStyle:{
                    normal: {
                        color: '#f3af33'
                    }
                },
                hoverAnimation: false
            }, {
                value: 100-data[i].ratio,
                name: '',
                label: {
                    normal: {
                        show: false
                    }
                },
                tooltip: {
                    show: false
                },
                itemStyle: {
                    normal: {
                        color: 'transparent'
                    },
                    emphasis: {
                        color: 'transparent'
                    }
                },
                hoverAnimation: false
            }]
        }]
    };

    // 使用刚指定的配置项和数据显示图表。
    pieChart[i].setOption(option[i]);
}

//编写渲染本周未处理事件柱状图函数
function renderBar(data){

    var provinceName = [];
    var alarmNum = [];
    var beforehand_alarmNum = [];
    var maintenanceNum = [];
    for(var i=0; i<data.length; i++){
        provinceName.push(data[i].province_name);//生成省份名称的数组
        alarmNum.push(data[i].alarm);//生成报警事件个数的数组
        beforehand_alarmNum.push(data[i].beforehand_alarm);//生成预警事件个数的数组
        maintenanceNum.push(data[i].maintenance);//生成保养事件个数的数组
    }

    // 基于准备好的dom，初始化echarts实例
    var barChart = echarts.init(document.getElementById('unhandledEvenbar'));

    var barOption = {
        color: ['#fb8404','#f3af33','#ffcf13'],
        tooltip : {
            trigger: 'axis'
        },
        legend: {
            x: 'right',
            padding: [12, 10, 0, 30],
            itemGap: 8,
            itemWidth: 6,
            itemHeight: 2,
            textStyle: {
                color: '#616368',
                fontSize: '12px',
                fontFamily: 'Microsoft YaHei'
            },

            data:['报警事件','预警事件','保养事件']
        },
        grid: {
            left: '2%',
            right: '3%',
            bottom: '0',
            containLabel: true
        },
        xAxis: [
            {
                show:true,
                axisLabel :{
                    interval:0,
                    textStyle: {
                        color: '#bababa',
                        fontSize: '12'
                    }
                },
                barGap: 0,
                type: 'category',
                data: provinceName,
                axisLine: {
                    lineStyle: {
                        color: '#f7f7f7',
                        width: 1,
                        type: 'dotted'
                    }
                },

                axisTick: {
                    show:false,
                    alignWithLabel: false
                }
            }],
        yAxis: [
            {
                type: 'value',
                barGap: 1,
                padding: 0,
                splitNumber: 3,
                splitLine: {
                    lineStyle:{
                        color: '#f8f8f8',
                        type: 'dotted'
                    }
                },

                axisLabel: {
                    formatter: '{value}',
                    textStyle: {
                        color: '#9d9d9d',
                        fontSize: '12'
                    }
                },
                axisLine: {
                    lineStyle: {
                        color: '#f7f7f7',
                        width: 1,
                        type: 'dotted'
                    }
                }
            }
        ],
        series : [
            {
                name:'报警事件',
                type:'bar',
                barWidth: '10',
                data:alarmNum,
                markpoint: {
                    label: {
                        normal :{
                            textStyle: {
                                color: '#fff'
                            }
                        }
                    }
                }
            },
            {
                name:'预警事件',
                type:'bar',
                barWidth: '10',
                data:beforehand_alarmNum
            },
            {
                name:'保养事件',
                type:'bar',
                barWidth: '10',
                data:maintenanceNum
            }
        ]
    };

    // 使用刚指定的配置项和数据显示图表。
    barChart.setOption(barOption);
}

//编写渲染地图的函数
function renderMap(data){

    var myChart5 = echarts.init(document.getElementById('map'));
    var convertData = function (data) {
        var res = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i].province_name) {
                res.push({
                    name: data[i].province_name,
                    value: [data[i].lng, data[i].lat, data[i].device_size]
                });
            }
        }
        // console.log(res);
        return res;
    };

    var option5 = {
        tooltip : {
            trigger: 'item'
        },

        geo: {
            map: 'china',
            label: {
                emphasis: {
                    show: false
                }
            },
            roam: false,
            itemStyle: {
                normal: {
                    areaColor: '#f4f5f5',
                    borderColor: '#bebebe'
                },
                emphasis: {
                    areaColor: '#bababa'
                }
            }
        },
        series : [
            {
                name: '',
                type: 'scatter',
                coordinateSystem: 'geo',
                data: convertData(data),
                symbolSize: function (val) {
                    return val[2] * 10;
                },
                label: {
                    normal: {
                        formatter: '{b}',
                        position: 'right',
                        show: false
                    },
                    emphasis: {
                        show: true
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#ecac3b'
                    }
                }
            },
            {
                name: 'Top 5',
                type: 'effectScatter',
                coordinateSystem: 'geo',
                data: convertData(data.sort(function (a, b) {
                    return b.value - a.value;
                }).slice(0, 6)),
                symbolSize: function (val) {
                    return val[2] *8;
                },
                showEffectOn: 'render',
                rippleEffect: {
                    brushType: 'stroke'
                },
                hoverAnimation: true,
                label: {
                    normal: {
                        formatter: '{b}',
                        position: 'right',
                        show: true
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#ecac3b',
                        shadowBlur: 10,
                        shadowColor: '#fffd38'
                    }
                },
                zlevel: 1
            }
        ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart5.setOption(option5);
}



$(function(){
    // ==========面包屑点击效果==========
    $('.top-list li').click(function() {
        $(this).addClass('active').siblings().removeClass('active');
    });

    //动态获取登录token
    var token = '';
    $.post("http://120.77.83.63:8180/baod/login.shtml",{username:"root",password:"xwl001"},
        function(data){
            if(data.code == "1"){
                token = data.data.token;
                query(token);
            }else{

            }
        },"json");


    var $normalRunNum= $('.normalRun .bar-num');
    var $alertNum= $('.alert .bar-num');
    var $normalStopNum= $('.normalStop .bar-num');

    var deviceNum = parseInt($('.deviceNum').text());


    var running_state = [];
    var on_line_state = [];
    var new_device = [];
    var device_event = [];

    function query(token){
        $.get('http://120.77.83.63:8180/baod/device/dataMonitoring.shtml',{token:token},function(data){
            console.log(data);
            if(data.code == '1') {
                running_state = data.data.running_state;
                on_line_state = data.data.on_line_state;

//              console.log(running_state.device_sum);

                $('.deviceNum').text(running_state.device_sum);//设备总数
                $normalRunNum.text(running_state.runing);//正常运行个数
                $alertNum.text(running_state.alarm);//报警状态个数
                $normalStopNum.text(running_state.stop);//正常停机个数

                $('.onlineNum').text(on_line_state.online);//在线个数
//                    console.log(on_line_state.online);
//                    console.log(on_line_state.offline);
                $('.offlineNum').text(on_line_state.offline);//离线个数
                $('.trafficWarn .bar-num').text(on_line_state.flow);//流量预警个数
                $('.longTimeOffline .bar-num').text(on_line_state.long_offline);//长时间不在线个数



                var deviceNum = running_state.device_sum;
                var normalRunPercent =running_state.run_rate;//正常运行百分比值
                var alertPercent =running_state.alarm_rate;//报警状态百分比值
                var normalStopPercent =running_state.stop_rate;//正常停机百分比值


                var onlinePercent =on_line_state.on_line_rate;//在线百分比值
                var trafficWarnPercent =on_line_state.flow_utilization;//流量比值
                var longTimeOfflinePercent =on_line_state.long_offline_rate;//长时间不在线


                //============进度条=============
                $("#normalRun").myProgress({speed: 1000, percent: normalRunPercent});
                $("#alert").myProgress({speed: 1000, percent: alertPercent});
                $("#normalStop").myProgress({speed: 1000, percent: normalStopPercent});
                $("#online").myProgress({speed: 1000, percent: onlinePercent, height: "12px", width: "162px"});
                $("#trafficWarn").myProgress({speed: 1000, percent: trafficWarnPercent});
                $("#longTimeOffline").myProgress({speed: 1000, percent: longTimeOfflinePercent});



                //========本周新增设备统计分析========

                new_device = data.data.new_device;
                var newProvince = new_device.province;

                $('.totalNum').text(new_device.total_add);//新增设备总数

                //新增幅度最大的Top5的省份,写入html中
                var $areaAdd_list = $('.areaAdd-list');
                var $areaAddLi = '';
                for(var i=0; i< newProvince.length; i++){
                    $areaAddLi += '<li>' +
                        '<div class="area-name fl">' + newProvince[i].province_name + '</div>' +
                        '<div class="area-num fr">' + newProvince[i].count +
                        '<span class="percent orange">' + newProvince[i].ratio + '%</span>' +
                        '</div>' +
                        '</li>';
                }
                $areaAdd_list.append($areaAddLi);//$areaAddLi插入$areaAdd_list


                //区域统计分析（饼状图）,写入html中
                var newRegion = new_device.region;
                var $pie_boxs = $('.pie-boxs');
                var pieBox = '';
                for(var i= 0; i<newRegion.length;i++){
                    pieBox += '<div class="pieBox">'+
                        '<div id="pie'+i+'" class="pie"></div>'+
                        '<div class="areatext">' +newRegion[i].region + '</div>'+
                        '</div>';
                }
                $pie_boxs.append(pieBox);//$pie_boxs插入$pie_boxs

                //循环调用渲染饼状图的函数
                for(var i= 0; i<newRegion.length;i++){
                    renderPie(newRegion,i);
                }




                //========== 本周未处理事件统计分析 ========
                device_event = data.data.device_event.device_event;
                // console.log(device_event[0].alarm);

                //调用渲染柱状图的函数
                renderBar(device_event);


                //=============  地图  =========
                renderMap(data.data.map);
            }
        },'json')
    }
})